/**
 * 图片广告  下一步
 */
var uploadVideoImgLength = 0; //图片张数
$(function (){
	//广告名称
	$("#adName").on("blur",function(){
		if(!$(this).val()){
			$("#mustVal").html("*必填").show();
		}else{
			$("#mustVal").hide();
		}
	});
	//广告链接
	$("#advUrl").on("blur",function(){
		if(!$(this).val()){
			$("#urlspan").html("*必填").show();
		}else{
			$("#urlspan").hide();
		}
	});
	//广告描述
	$("#description").on("blur",function(){
		if(!$(this).val()){
			$("#descriptspan").html("*必填").show();
		}else{
			$("#descriptspan").hide();
		}
	});
	$(".uploadNav ul").find("li").click(function(){
		$(this).addClass("selectedUploaded");
		$(this).siblings("li").removeClass("selectedUploaded");
	});
	$("#imgUrl").val("");
	$("#imgSize").val("");
	
	//正则验证
	function mustval(){ //非空验证
		var adNameVal=$("#adName").val();
		var mustVal=/^\S|\S$/;
		if(mustVal.test(adNameVal)){
			return true;
		}else{
			return false;
		}
	};
	//关键字校验
	 function keyletter(keyval){
	 	  var patKey=/^[A-Za-z0-9\u4e00-\u9fa5]+$/;
	 	  if(patKey.test(keyval)){
	 		 return true;
	 	  }else{
	 		 return false;
	 	  } 
	  };
	  $("#keyPat").hide();
	  $("#keyPat2").hide();
	  $("#keyPat3").hide();
	  $("#keyPat4").hide();
	  $("#keyPat5").hide();
	  $("#keyPat6").hide();
	  
	  $("#key1").on("blur",function(){
		  var keyVal=$("#key1").val();
		  var result=keyletter(keyVal);
		  if(!$(this).val()){
		 	  $("#keyPat").html("*必填").css("right","-1px").show();
		  }else if(result){
		 	  $("#keyPat").hide();
		  }else{
		 	  $("#keyPat").html("*由中文、数字、英文组成").css("right","-125px").show();
		  }
	  });
	  $("#key2").on("blur",function(){
		  keyWordPattern($("#key2"),$("#keyPat2"));
	  });
	  $("#key3").on("blur",function(){
		  keyWordPattern($("#key3"),$("#keyPat3"));
	  });
	  $("#key4").on("blur",function(){
		  keyWordPattern($("#key4"),$("#keyPat4"));
	  });
	  $("#key5").on("blur",function(){
		  keyWordPattern($("#key5"),$("#keyPat5"));
	  });
	  $("#key6").on("blur",function(){
		  keyWordPattern($("#key6"),$("#keyPat6"));
	  });
	  function keyWordPattern(key,keypat){
		  var keyVal=key.val();
		  var result=keyletter(keyVal);
		  if(!key.val()){
			  keypat.hide();
		  }else if(result){
			  keypat.hide();
		  }else{
		      keypat.show();
		  }
	  }
	 function keyPatFun(){
		 var keyPat2=$("#keyPat2").css("display");
		 var keyPat3=$("#keyPat3").css("display");
		 var keyPat4=$("#keyPat4").css("display");
		 var keyPat5=$("#keyPat5").css("display");
		 var keyPat6=$("#keyPat6").css("display");
		 if(keyPat2=="block" || keyPat3=="block" || keyPat4=="block" ||keyPat5=="block" ||keyPat6=="block" ){
			 return true;
		 }else{
			 return false;
		 }
	 }
	$("body").on("mouseover",function(){
		 var keyVal=$("#key1").val();
		//广告属性  
		 var Achecked=$(".adTargetModalBox img[data-target='1']");
		 if(Achecked.length!=0){
			 $(".targetAlert").hide();
		 }else{
			 $(".targetAlert").show();
		 }
		 var dataLoading=$(".adCoverUploadImgBox li").last().attr("data-loading");
		 var imgSrc=$("#adHomeImg").attr("src");
		 var advUrl = $("#advUrl").val();
		 if( advUrl && imgSrc && $("#adName").val() && $("#description").val()&& keyletter(keyVal) && dataLoading=="loaded" && !keyPatFun() && Achecked.length!=0){
			 $(".modifyImgSignBtn").attr("disabled",false);
			
		 }else{
			 $(".modifyImgSignBtn").attr("disabled",true);
		 }
	 });

	$(".modifyImgSignBtn").on("click",function(){
		savePictureAd();
		$(".modifyImgSignBtn").off();
	})
});
var adHomepage = "";//图片广告封面
function savePictureAd(){
	var terminalType = "";//终端
	//上传主页
	if(adHomepage.length !=0){

			terminalType =  transitionFTerminalTyp($(".selectedUploaded span").html());//终端
			var imgUrl = $("#imgUrl").val();
			var imgSize =$("#imgSize").val();
			if(imgUrl.length !=0){
				saveAd(imgSize,imgUrl,terminalType,adHomepage);
			}else{
				alert("请上传广告图片!")
			}

	}else{
		alert("请填写内容！")
	}
}

var saveAd = function(imgSize,imgUrl,terminalType,adHomepage){
	var name = $("#adName").val();//广告名
	var advUrl = $("#advUrl").val(); //广告链接
	var description =  $("#description").val();//描述
	var duration = $("#duration").html();//图片张数
	
	
	//关键字
	var adKey ="";
	var key1 = $("#key1").val();
	var key2 = $("#key2").val();
	var key3 = $("#key3").val();
	var key4 = $("#key4").val();
	var key5 = $("#key5").val();
	var key6 = $("#key6").val();
	if(key1.length !=0 ){adKey += key1+"|";}
	if(key2.length !=0 ){adKey += key2+"|";}
	if(key3.length !=0 ){adKey += key3+"|";}
	if(key4.length !=0 ){adKey += key4+"|";}
	if(key5.length !=0 ){adKey += key5+"|";}
	if(key6.length !=0 ){adKey += key6+"|";}

	var adClassify = "";  
	var Achecked=$(".adTargetModalBox img[data-target='1']");
	$.each(Achecked,function(index){
		adClassify +=Achecked[index].id+"|";
	})

	$.ajax({
		url : '/web-adv/savePictureAd',
        data:{	
	        	name:name,
	        	advUrl:advUrl,
	        	description:description,
	        	adHomepage:adHomepage,
	        	adKey:adKey,
	        	terminalType:terminalType,
				imgUrl:imgUrl,
				imgSize:imgSize,
				adClassify:adClassify,
				duration:duration
	        	},
		type : 'post',
		success : function(data) {
			if(data.resultVo.status=="1"){
				var adCode = data.adCode;
				window.location.href="/web-adv/advWeb/views/uploadAd/imageAd/uploadCheck.html?selectedNav=1&navPos=2&adCode="+adCode;
			}else{
				alert("保存失败");
			}
		},
        error: function(){}        
	});	
	
}


function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {type: mimeString});
}
//------------------吴-----------------------------

var uploadImg = {
	     change:function(e,ele){
		     var fs = new FileReader(),files = e.files[0];
			 var fileName = files.name;
			 if(files.size>10*1024*1024 ||files.size<10*1024 ){
				 console.log("==========="+files.size)
				alert("单照图片在10K-10M之间，请您重新选择图片！");
			 }else {
				 if(!uploadImg.isSuffix(fileName)) return false;//判断图片格式
				 //超过9个时按钮禁用
				 $("body").on("mousemove",function(){
					 if($(".adCoverUploadImgBox").find('li').length>=9){
						 $(".disableBtn").css("cursor","not-allowed");
						 $(".disableBtn").attr("disabled",true);
					 }else{
						 $(".disableBtn").css("cursor","pointer");
						 $(".disableBtn").attr("disabled",false);
					 }
				 })
				 fs.readAsDataURL(files);
				 fs.onload = function(event){
					 if(ele.parent().next().find('li').length>8){
						 alert("最多只能9张图片，请先删除不需要的图片后再上传");
					 }else{
						 /**var terminal = $(".uploadNav").find(".selectedUploaded").attr('data-terminal'),addArr;
						  switch(terminal){
     					 case "pc":
						 addArr = uploadImg.pc;
						 break;
						 case "mob":
						 addArr = uploadImg.mob;
						 break;
						 case "pad":
						 addArr = uploadImg.pad;
						 break;
						 default:
						 addArr = uploadImg.tv;
					 };
						  addArr.push(this.result);**/
						 var src = this.result;
						// console.log(src);
						 var html = '<li data-loading="select"><span onclick="uploadImg.delegate($(this))">X</span>'+
							 '<img src="'+src+'" alt="" />'+
							 '</li>';
						 ele.parent().next().append(html);
						 var fd = new FormData();
						 var blob = dataURItoBlob(src);
						 fd.append('file', blob,fileName);

						  $.ajax({
							 url : '/web-adv/uploadImgs',
							 type : 'post',
							 data:fd,
							 processData: false, // 不会将 data 参数序列化字符串
							 contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
							 success : function(data) {
								 var data=JSON.parse(data);
								 //console.log(data.data)
								 if(data.status=="1"){ //已上传成功
									 //保存 所有
									 uploadVideoImgLength++;
									 $("#duration").text(uploadVideoImgLength);
									 $("#imgUrl")[0].value +="|"+data.data;
									 $("#imgSize")[0].value +="|"+data.fileSize;

									 ele.parent().next().children("li").attr("data-loading","loaded");
								 }else{
									 alert("保存失败！");
								 }
							 },
							 error: function(){}
						 });
					 }
				 }
			 }

		 },
		 changeHomeImage:function(e,ele){				    
		     var fs = new FileReader(),files = e.files[0];
			 var fileName = files.name;
			 if(files.size>10*1024*1024 ||files.size<10*1024 ){
				 console.log("======封面====="+files.size)
				 alert("单照图片在10K-10M之间，请您重新选择图片！");
			 }else {
				 if(!uploadImg.isSuffix(fileName)) return false;//判断图片格式
				 fs.readAsDataURL(files);
				 fs.onload = function(event){
					 /*console.log(ele.parent("div.uploadBtnBg").siblings("img").length);*/
					 ele.parent("div.uploadBtnBg").siblings("img").attr("src",this.result);
					 //上传封面
					 var fd = new FormData();
					 var blob = dataURItoBlob(this.result);
					 fd.append('file', blob,fileName);
					 $.ajax({
						 url : '/web-adv/uploadImgs',
						 type : 'post',
						 data:fd,
						 processData: false, // 不会将 data 参数序列化字符串
						 contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
						 success : function(data) {
							 var data=JSON.parse(data);
							 //console.log(data.data)
							 if(data.status=="1"){
								 //保存 所有
								 adHomepage = data.data;
							 }else{
								 alert("保存失败！");
							 }
						 },
						 error: function(){}
					 });
				 }
			 }
		 },
		 delegate:function(ele){
		     /**var terminal = $(".uploadNav").find(".selectedUploaded").attr('data-terminal'),addArr,src=ele.next().attr("src");
			 switch(terminal){
			     case "pc":
				 addArr = uploadImg.pc;
				 break;
				 case "mob":
			     addArr = uploadImg.mob;
				 break;
				 case "pad":
			     addArr = uploadImg.pad;
				 break;
				 default:
				 addArr = uploadImg.tv;
			 };	
			 for(var i=0;i<addArr.length;i++){
			     if(addArr[i]==src){
				     addArr.splice(i,1); 
				 }
			 }**/
			 var eleIndex = ele.parent().index();//
			 uploadVideoImgLength --;//图片张数
			 $("#duration").text(uploadVideoImgLength);

			 //图片url
			 var imgArr = $("#imgUrl").val().split("|");//切割多个url字符串
			 //console.log(imgArr);
			 imgArr.splice(eleIndex+1,1);//从一个数组中移除一个或多个元素
			 //console.log(imgArr); //移除后的url
			 var newImgArr="";
			 for(var i=1;i<imgArr.length;i++){
				 newImgArr+="|" + imgArr[i];
			 };
			 $("#imgUrl").val(newImgArr);
			 //console.log(newImgArr);

			 //删除时 计算图片大小
			 var imgSizeArr = $("#imgSize").val().split("|");//切割多个fileSize字符串
			 imgSizeArr.splice(eleIndex+1,1);//从一个数组中移除一个或多个元素
			 //console.log("后"+imgSizeArr);
			 var newImgSizeArr = "";
			 for (var i=1;i<imgSizeArr.length;i++){
				 newImgSizeArr+="|" + imgSizeArr[i];
			 }
			// console.log(newImgSizeArr);
			 $("#imgSize").val(newImgSizeArr);


		     ele.parent().remove();
		 },
		 toggleNav:function(ele){				    
			 //$(".adCoverUploadImgBox").empty();
			 /**var terminal = ele.attr('data-terminal');
			 switch(terminal){
			     case "pc":
				 addArr = uploadImg.pc;
				 break;
				 case "mob":
			     addArr = uploadImg.mob;
				 break;
				 case "pad":
			     addArr = uploadImg.pad;
				 break;
				 default:
				 addArr = uploadImg.tv;
			 };						 
            for(var i=0;i<addArr.length;i++){
			     var html = '<li><span onclick="uploadImg.delegate($(this))">X</span>'+
				 '<img src="'+addArr[i]+'" alt="" />'+
				 '</li>';
			     $(".adCoverUploadImgBox").append(html);
			 }								
			 ele.parent().next().append(html);**/
			 ele.addClass("selectedUploaded");
	         ele.siblings("li").removeClass("selectedUploaded");
		 },
		isSuffix:function(ele){
			ele = ele.substring(ele.lastIndexOf(".")+1,ele.length);
			ele=ele.toUpperCase();//jpg、gif、png
			if(ele!="PNG"&&ele!="GIF"&&ele!="JPEG"&&ele!="JPG"){
				alert("请您上传jpg、gif、png格式的图片！")
				return false;
			}
			return true;
		}
		 /**mob:[],
		 pc:[],
		 pad:[],
		 tv:[],**/
	 };
    $(".uploadNav ul").find("li").click(function(){
	     uploadImg.toggleNav($(this));
	 });
